package com.yoda.youdianda.interceptor;

import com.yoda.youdianda.common.RC;
import com.yoda.youdianda.common.ThreadContext;
import com.yoda.youdianda.domain.SysUser;
import com.yoda.youdianda.domain.YddUser;
import com.yoda.youdianda.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class TokenInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截到路径：{}",request.getRequestURI());
        //获取token
        String token = request.getHeader("x-token");
        String frontToken = request.getHeader("token");
        //当两个token均无效时
        if ((StringUtils.isEmpty(token)||!JwtUtils.verifyToken(token))&&(StringUtils.isEmpty(frontToken)||!JwtUtils.verifyToken(frontToken))){
            //无token或者token失效返回false
            response.setStatus(401);
            return false;
        }
        if (StringUtils.isNotEmpty(token)) {
            Claims claims = JwtUtils.getClaims(token);
            String id = (String) claims.get("id");
            String loginName = (String) claims.get("loginName");
            SysUser user = new SysUser();
            user.setId(id);
            user.setLoginName(loginName);
            //存入线程变量副本
            ThreadContext.setObject(RC.SYS_USER,user);
            return true;
        }
        if (StringUtils.isNotEmpty(frontToken)){
            Claims claims = JwtUtils.getClaims(frontToken);
            String id = claims.get("id").toString();
            String phone = (String) claims.get("mobile");
            YddUser yddUser = new YddUser();
            yddUser.setId(Integer.parseInt(id));
            yddUser.setMobile(phone);
            //存入线程变量副本
            ThreadContext.setObject(RC.YDD_USER,yddUser);
            return true;
        }

        return false;
    }

    /**
     * 访问结束后清除变量副本
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理程序
     * @param ex       前女友
     * @throws Exception 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// TODO: 2022/11/17 解决方案访问结束后不清除变量副本 
//            ThreadContext.clear();
    }
}